/*
	Copyright (c) 2008 Memorphic Ltd. All rights reserved.
	
	Redistribution and use in source and binary forms, with or without 
	modification, are permitted provided that the following conditions 
	are met:
	
		* Redistributions of source code must retain the above copyright 
		notice, this list of conditions and the following disclaimer.
	    	
	    * Redistributions in binary form must reproduce the above 
	    copyright notice, this list of conditions and the following 
	    disclaimer in the documentation and/or other materials provided 
	    with the distribution.
	    	
	    * Neither the name of MEMORPHIC LTD nor the names of its 
	    contributors may be used to endorse or promote products derived 
	    from this software without specific prior written permission.
	
	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
	"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
	LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
	A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
	OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
	SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 
	LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
	DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 
	THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
	(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
	OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package memorphic.slide.metadata
{
	
	import mx.binding.utils.ChangeWatcher;
	import mx.utils.DescribeTypeCache;
	
	
	/**
	 * Implements the [Trigger] metadata.
	 * 
	 * <code>[Trigger]</code> may be used to annotate any singe-argument method or writable property, provided that it is publicly
	 * accessible, that is <code>public</code> or in a namespace (i.e. not <code>protected</code>, <code>private</code> or <code>internal</code>.)
	 * 
	 * You can use the namespace <code>slide_private</code> to indicate the intent that a property be private, while still allowing
	 * <code>[Trigger]</code> to work. 
	 */
	public class TriggerMetadataImpl
	{
		
		public var host:Object;
		
		
		
		/**
		 * @param host Object. The host to which trigger capabilities should be added
		 * @param useMetadata Boolean. If true (default) then the host's type will be automatically introspected to find [Trigger] metadata
		 */
		public function TriggerMetadataImpl(host:Object, useMetadata:Boolean=true)
		{
			this.host = host;
			if(useMetadata){
				setupTriggers();
			}
		}
		
		protected function setupTriggers():void
		{
			var type:XML = DescribeTypeCache.describeType(host).typeDescription;
			var triggers:Array = new TriggerInfo(type).getTriggers();
			var triggerItem:TriggerInfoItem;
			for(var i:int=0; i<triggers.length; i++){
				triggerItem = triggers[i] as TriggerInfoItem;
				var func:Function;
				if(triggerItem.isSetter){
					addTriggerProperty(triggerItem.path, host, triggerItem.methodName, triggerItem.nsURI, triggerItem.commitOnly, triggerItem.triggerOnce);
//					func = new SetterTrigger(host, triggerItem.methodName, triggerItem.nsURI, triggerItem.path).handler;
				}else{
					addTriggerFunction(triggerItem.path, host, triggerItem.methodName, triggerItem.nsURI, triggerItem.commitOnly, triggerItem.triggerOnce);
//					func = new MethodTrigger(host, triggerItem.methodName, triggerItem.nsURI, triggerItem.path).handler;
				}
			}
		}
		
		
		/**
		 * Manually add a trigger, without metadata.
		 * This is handy, for example, if using a pre-compiler to remove [Trigger] metadata, which would remove the need for the trigger host type to be 
		 * introspected at runtime.
		 */
		public function addTriggerProperty(path:Array, host:Object, propertyName:String, propertyNsURI:String=null, commitOnly:Boolean=false, triggerOnce:Boolean=false):void
		{
			var func:Function = new SetterTrigger(host, propertyName, propertyNsURI, path, triggerOnce).handler;
			ChangeWatcher.watch(host, path, func, commitOnly);
		}
		
		public function addTriggerFunction(path:Array, host:Object, methodName:String, methodNsURI:String=null, commitOnly:Boolean=false, triggerOnce:Boolean=false):void
		{	
			var func:Function = 
				new MethodTrigger(host, methodName, methodNsURI, path, triggerOnce).handler;
			ChangeWatcher.watch(host, path, func, commitOnly);
		}
	}
}



import flash.events.Event;
import mx.logging.Log;
import flash.events.IEventDispatcher;


class BaseTrigger
{
	public var host:Object;
	public var chain:Array;
	public var triggerOnce:Boolean;
	
	public function BaseTrigger(host:Object, chain:Array, triggerOnce:Boolean)
	{
		this.host = host;
		this.chain = chain;
		this.triggerOnce = triggerOnce;
	}
	
	protected function getValue():*
	{
		try{
			var n:int = chain.length;
			var value:Object = host;
			for(var i:int=0; i<n; i++){
				value = value[chain[i]];
			}
		}catch(e:Error){
			Log.getLogger( "memorphic.slide.metadata.TriggerMetadataImpl" ).warn("[Trigger] Error peforming binding to '" + chain.join(".") + "'.");
		}
		return value;
	}
}

class SetterTrigger extends BaseTrigger
{
	public var propName:*;
	
	public function SetterTrigger(host:Object, propName:String, nsURI:String, chain:Array, triggerOnce:Boolean)
	{
		super(host, chain, triggerOnce);
		if(!nsURI){
			this.propName = propName;
		}else{
			this.propName = new QName(new Namespace(nsURI), propName);
		}
	}
	
	public function handler(e:Event):void
	{
		var value:*;
		try {
			value = getValue();
			host[propName] = value;
		}catch(e:Error){
			Log.getLogger( "memorphic.slide.metadata.TriggerMetadataImpl" ).error("[Trigger] Error binding to setter. " + e.message);
		}
		if(triggerOnce && value != null){
			IEventDispatcher(e.target).removeEventListener(e.type, handler);
		}
	}
}


class MethodTrigger  extends BaseTrigger
{
	public var methodName:*;
	
	public function MethodTrigger(host:Object, methodName:String, nsURI:String, chain:Array, triggerOnce:Boolean)
	{
		super(host, chain, triggerOnce);
		
		if(!nsURI){
			this.methodName = methodName;
		}else{
			this.methodName = new QName(new Namespace(nsURI), methodName);
		}
	}
	

	public function handler(e:Event):void
	{
		var value:*;
		try {
			value = getValue();
			host[methodName](value);
		}catch(e:Error){
			Log.getLogger( "memorphic.slide.metadata.TriggerMetadataImpl" ).error("[Trigger] Error binding to method. " + e.message);
		}catch(e:ArgumentError){
			try{
				host[methodName]();
			}catch(e2:Error){
				Log.getLogger( "memorphic.slide.metadata.TriggerMetadataImpl" ).error("[Trigger] Error binding to method. " + e.message);
			}
		}
		if(triggerOnce && value != null){
			IEventDispatcher(e.target).removeEventListener(e.type, handler);
		}
	}
}

